package com.unhz.taigu.service.impl;

import com.unhz.generator.dao.DeliveryOrderMapper;
import com.unhz.generator.dao.ProductionOrderInfoMapper;
import com.unhz.generator.dao.ProductionOrderMapper;
import com.unhz.generator.dao.SysRolePermissionMapper;
import com.unhz.generator.enums.*;
import com.unhz.generator.pojo.*;
import com.unhz.generator.utils.EmptyUtil;
import com.unhz.generator.utils.IsNumeric;
import com.unhz.generator.utils.Page;
import com.unhz.generator.vo.DeliveryOrderVo;
import com.unhz.generator.vo.OrderVo;
import com.unhz.generator.vo.TryOrderVo;
import com.unhz.taigu.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: 王林恩
 * @Description:
 * @Date: Created in 上午 9:01 2018/2/1 0001
 * @Modified By:
 */
@Service
public class DeliveryOrderServiceImpl implements DeliveryOrderService {

    static final int PAGENUM = 1;
    @Autowired
    private DeliveryOrderMapper deliveryOrderMapper;
    @Autowired
    private DeliveryInfoService deliveryInfoService;
    @Autowired
    private WsDictService wsDictService;
    @Autowired
    private ProductionOrderService productionOrderService;
    @Autowired
    private ProductionOrderInfoMapper productionOrderInfoMapper;
    @Autowired
    private ProductionOrderMapper productionOrderMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ContractService  contractService;
    @Autowired
    private ReceivingInfoService receivingInfoService;
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    /**
     * 根据交货订单id查询订货订单
     * @param id 交货订单Id
     * @return
     */
    @Override
    public DeliveryOrder findDeliveryOrder(Long id) {
        return deliveryOrderMapper.selectByPrimaryKey(id);
    }
    /**
     * 分页查询
     * @param pageNo 页数
     * @param keywords 关键词
     * @return
     */
    @Override
    public Page<DeliveryOrderVo> findAllDeliveryOrder(String pageNo, Integer pageSize, String keywords,Integer adminId,Integer roleId) {
        int pageNum = PAGENUM;
        boolean numok = IsNumeric.isNumeric(pageNo);
        if(numok){
            if(pageNo !=null && !"".equals(pageNo)){
                pageNum = Integer.parseInt((pageNo));// 页数
            }
        }
        //查询roleId中是否存在permissionId对应值的权限
        int count = sysRolePermissionMapper.selectPermissionIdByRoleIdOrder(roleId);
        //获取记录总条数
        int totalRecords = 0;
        if(1==count){
            totalRecords = deliveryOrderMapper.selectCountByKey(keywords);        //获取记录总条数
        }else{
            totalRecords = deliveryOrderMapper.selectCountByAdminId(adminId,keywords);
        }
        Page page = new Page(pageNum,totalRecords);
        page.setPageSize(pageSize);
        Map<String ,Object> map = new HashMap<String,Object>();
        map.put("startIndex",page.getStartIndex());
        map.put("pageSize",page.getPageSize());
        map.put("keywords",keywords);
        map.put("adminId",adminId);
        //获取总记录数
        List<DeliveryOrderVo> records = new ArrayList<DeliveryOrderVo>();
        if(1==count){
            records= deliveryOrderMapper.selectAllDeliveryOrder(map);
        }else{
            records = deliveryOrderMapper.selectAllDeliveryOrderByAdminId(map);
        }
        for(DeliveryOrderVo deliveryOrderVo:records){
            List<DeliveryInfo> infoList = deliveryInfoService.findDeliveryInfoByDeliveryOrderId(Long.valueOf(deliveryOrderVo.getDeliveryOrderId()));
            deliveryOrderVo.setDeliveryOrderList(infoList);
        }
        page.setRecords(records);
        String uri = "/deliveryOrder/findDeliveryOrder?keywords="+keywords+"&roleId="+roleId+"&adminId="+adminId;
        page.setUri(uri);
        return page;
    }

    @Override
    public int findCountDeliveryOrder(String keywords) {
        return deliveryOrderMapper.selectCountByKey(keywords);
    }

    @Override
    public int addDeliveryOrder(DeliveryOrder deliveryOrder,String [] size,String [] number) {
        ProductionOrder productOrder = productionOrderService.selectById(Integer.parseInt(deliveryOrder.getProductionId().toString()));
        List<DeliveryOrder> deliveryOrderList = deliveryOrderMapper.selectByProductionId(productOrder.getId().toString());
        int batch = deliveryOrderList.size()+1;
        //batch++;
        deliveryOrder.setDeliveryNo(productOrder.getProductionNo()+"C"+batch);
        Date nowTime = new Date(System.currentTimeMillis());
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyyMMddhhmmssSSS");
        String retStrFormatNowDate = sdFormatter.format(nowTime);
        if ("".equals(deliveryOrder.getCounties())||deliveryOrder.getCounties()==null){
            //物流运单号规则：日期时间（毫秒级）+收货区代码（如果没有区代码就为市代码）
            deliveryOrder.setWaybillNo(retStrFormatNowDate+deliveryOrder.getCity());//收货地址-市的行政编码,生成运单号
        }else {
            deliveryOrder.setWaybillNo(retStrFormatNowDate+deliveryOrder.getCounties());//收货地址-区/县的行政编码,生成运单号
        }
        deliveryOrder.setValid((byte) EnumValid.ENABLED.getIndex());
        deliveryOrder.setStatus((byte) EnumStatus.CHECKING.getIndex());
        int res = deliveryOrderMapper.insertSelective(deliveryOrder);
        DeliveryOrder deliveryOrder1 = deliveryOrderMapper.selectDeliveryOrderByKey(deliveryOrder.getDeliveryNo(),deliveryOrder.getProductionId().toString());
        for (int i=0;i<size.length;i++){
            DeliveryInfo deliveryInfo = new DeliveryInfo();
            deliveryInfo.setDeliveryId(deliveryOrder1.getId());
            deliveryInfo.setValid((byte) EnumValid.ENABLED.getIndex());
            deliveryInfo.setSize(size[i]);
            deliveryInfo.setNumber(Integer.parseInt(number[i]));
            deliveryInfoService.addDeliveryInfo(deliveryInfo);
        }
        return res;
    }

    @Override
    public int deleteDeliveryOrderById(Long id) {
        int res = deliveryInfoService.deleteDeliveryInfo(id);
        return deliveryOrderMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateDeliveryOrder(DeliveryOrder deliveryOrder) {
        return deliveryOrderMapper.updateByPrimaryKeySelective(deliveryOrder);
    }

    @Override
    public DeliveryOrder findBy(String deliveryNo,String productionId) {
        return deliveryOrderMapper.selectDeliveryOrderByKey(deliveryNo,productionId);
    }

    @Override
    public void updateDeliveryOrderStatus(Integer deliveryId, int status) {

        DeliveryOrder deliveryOrder = deliveryOrderMapper.selectByPrimaryKey(Long.valueOf(deliveryId));
        deliveryOrder.setStatus((byte) status);
        deliveryOrderMapper.updateByPrimaryKeySelective(deliveryOrder);


        ProductionOrder productOrder = productionOrderService.selectById(Integer.parseInt(deliveryOrder.getProductionId().toString()));
        List<ProductionOrderInfo> productionOrderInfoList = productionOrderInfoMapper.selectByOrderId(Long.valueOf(deliveryOrder.getProductionId()));
        int productCount = 0;
        for (int i=0;i<productionOrderInfoList.size();i++){
            productCount+=productionOrderInfoList.get(i).getNumber();
        }
        List<DeliveryOrder> deliveryOrderList = deliveryOrderMapper.selectByProductionId(deliveryOrder.getProductionId().toString());
        List<DeliveryInfo> deliveryInfoList = deliveryInfoService.findDeliveryInfoByDeliveryOrderId(deliveryOrder.getId());
        int deliveryCount = 0;
        for (DeliveryOrder dOrder:deliveryOrderList){
            if (dOrder.getStatus()==Byte.parseByte(String.valueOf(EnumDeliveryOrder.FINISH_DELIVERY.getIndex()))){
                for (DeliveryInfo deliveryInfo:deliveryInfoList){
                    deliveryCount+=deliveryInfo.getNumber();
                }
            }
        }
        if (productCount==deliveryCount&&productCount!=0){
            productOrder.setStatus((byte) EnumProductionOrder.FINISH.getIndex());
            int res = productionOrderMapper.updateByPrimaryKeySelective(productOrder);


            List<Contract> contractList = contractService.findContractsByOrderId(Integer.parseInt(productOrder.getOrderId().toString()));
            int contractCount = 0;
            for (Contract contract:contractList){
                contractCount+=contract.getNumber();
            }
            int allProductCount = 0;
            List<ProductionOrder> productionOrderList = productionOrderService.selectByOrderId(Long.valueOf(productOrder.getOrderId()));
            for (ProductionOrder productionOrder:productionOrderList){
                for (int i=0;i<productOrder.getProductionOrderInfoList().size();i++){
                    allProductCount+=productionOrder.getProductionOrderInfoList().get(i).getNumber();
                }
            }
            if (contractCount==allProductCount&&contractCount!=0){
                //Order order = orderService.selectOrderById(Integer.parseInt(productOrder.getOrderId().toString()));
            }

        }

    }

    @Override
    public List<DeliveryOrder> findByProductionId(String productionId) {
        return deliveryOrderMapper.selectByProductionId(productionId);
    }

    @Override
    public int deleteDeliveryOrder(Long deliveryId) {
        return deliveryOrderMapper.deleteDeliveryOrderid(deliveryId);
    }

    @Override
    public List<DeliveryOrder> selectDeliveryOrder(Long productionId) {
        return deliveryOrderMapper.selectDeliveryOrder(productionId);
    }

    @Override
    public DeliveryOrder selectNewDeliveryOrder(Long productionId) {
        return deliveryOrderMapper.selectNewDeliveryOrder(productionId);
    }

    @Override
    public int insertDeliveryOrder(DeliveryOrder deliveryOrder) {
        return deliveryOrderMapper.insertSelective(deliveryOrder);
    }
}
